package com.newlink.building.login.mvp.presenter

import android.content.Context
import android.content.Intent
import com.newlink.building.login.mvp.contract.Module_Login_RegisterContract
import com.newlink.building.login.mvp.model.Module_Login_RegisterModel
import com.newlink.building.common_base.base.BasePresenter
import com.newlink.building.common_base.ext.registerThen
import com.newlink.building.common_base.model.bean.KitDeviceData
import com.newlink.building.common_base.model.bean.KitRegisterRequest
import com.newlink.building.common_base.model.bean.VerifyCodeRequest
import com.newlink.building.common_base.utils.logDebug
import org.json.JSONArray
import androidx.core.net.toUri

/**
 * Created by xiaodong on 2022/8/24.
 */
class Module_Login_RegisterPresenter : BasePresenter<Module_Login_RegisterContract.Model, Module_Login_RegisterContract.View>(),
    Module_Login_RegisterContract.Presenter {

    override fun createModel(): Module_Login_RegisterContract.Model? = Module_Login_RegisterModel()
    override fun register(username: String, password: String) {
       logDebug<Module_Login_RegisterPresenter>("register $username $password")
        mModel?.register(username, password)?.registerThen(mModel, mView) {
//            mView?.registerSuccess(it.data)
        }
    }

    override fun kitRegister(request: KitRegisterRequest) {
        mModel?.kitRegister(request)?.registerThen(mModel, mView) {
            mView?.registerSuccess(it.data)
        }
    }

    override fun getVerifyCode(request: VerifyCodeRequest) {
        mModel?.getVerifyCode(request)?.registerThen(mModel, mView) {
            mView?.getVerifyCodeSuccess(it.code == 200)
        }
    }

    override fun startBrowser(context: Context, url: String) {
        val intent = Intent()
        intent.action = "android.intent.action.VIEW"
        intent.data = url.toUri()
        intent.setClassName(
            "com.android.browser",
            "com.android.browser.BrowserActivity"
        )
        context.startActivity(intent)
    }

    override fun getKitDeviceDataFromQrcode(qrcode: String): ArrayList<KitDeviceData> {
        var deviceDatas = arrayListOf<KitDeviceData>()

        try {
            val jsonArray = JSONArray(qrcode)
            for (i in 0 until jsonArray.length()) {
                val jsonObj = jsonArray.getJSONObject(i)
                val name = jsonObj.optString("name")
                val mac = jsonObj.optString("mac")
                val type = jsonObj.optInt("type")
                val doors = jsonObj.optInt("doors")
                deviceDatas.add(KitDeviceData(name = name, mac = mac, type = type, doors = doors))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        logDebug<Module_Login_RegisterPresenter>("getKitDeviceDataFromQrcode response ->  二维码解析结果...${deviceDatas}")
        return deviceDatas
    }
}